//查询所有考试
<template>
  <div class="exam">
    <el-table :data="pagination.records" border @expand-change="changeExpand">
      <el-table-column type="expand" label="预览试卷" width="120">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item>
              <h3 style="margin-left: 20px">{{ props.row.source }}<i class="header-icon el-icon-info"></i></h3>
              <span class="time">{{ examData.totalScore }}分 / {{ examData.totalTime }}分钟</span>
            </el-form-item>
            <el-form-item>
              <el-collapse class="inner">
                <!--选择题-->
                <el-collapse-item>
                  <template slot="title" name="1">
                    <div class="titlei">选择题 (共{{ topicCount[0] }}题 共计{{ score[0] }}分)</div>
                  </template>
                  <div class="contenti">
                    <ul class="question" v-for="(list, index) in topic[1]" :key="index">
                      <li>{{ index + 1 }}. {{ list.question }} {{ list.score }}分</li>
                      <el-radio label="A">A：{{list.answerA}}</el-radio>
                      <el-radio label="B">B：{{list.answerB}}</el-radio>
                      <el-radio label="C">C：{{list.answerC}}</el-radio>
                      <el-radio label="D">D：{{list.answerD}}</el-radio>
                      <el-tag type="success">正确答案：{{list.rightAnswer}}</el-tag>
                      <el-tag type="info" v-if="list.analysis === null">解析：略</el-tag>
                      <el-tag type="info" v-else>解析：{{list.analysis}}</el-tag>
                    </ul>
                  </div>
                </el-collapse-item>
                <!--填空题-->
                <el-collapse-item>
                  <template slot="title" name="2">
                    <div class="titlei">填空题 (共{{ topicCount[1] }}题 共计{{ score[1] }}分)</div>
                  </template>
                  <div class="contenti">
                    <ul class="question" v-for="(list, index) in topic[2]" :key="index">
                      <li>{{ topicCount[0] + index + 1 }}.{{ list.question }} {{ list.score }}分</li>
                      <el-tag type="success">正确答案：{{list.answer}}</el-tag>
                      <el-tag type="info" v-if="list.analysis === null">解析：略</el-tag>
                      <el-tag type="info" v-else>解析：{{list.analysis}}</el-tag>
                    </ul>
                  </div>
                </el-collapse-item>
                <el-collapse-item>
                  <template slot="title" name="3">
                    <div class="titlei">判断题 (共{{ topicCount[2] }}题 共计{{ score[2] }}分)</div>
                  </template>
                  <div class="contenti">
                    <ul class="question" v-for="(list, index) in topic[3]" :key="index">
                      <li>{{ topicCount[0] + topicCount[1] + index + 1 }}. {{ list.question }} {{ list.score }}分</li>
                      <el-tag type="success" v-if="list.answer==='F'">正确答案：错</el-tag>
                      <el-tag type="success" v-else-if="list.answer==='T'">正确答案：对</el-tag>
                      <el-tag type="info" v-if="list.analysis === null">解析：略</el-tag>
                      <el-tag type="info" v-else>解析：{{list.analysis}}</el-tag>
                    </ul>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column prop="source" label="试卷名称" width="120"></el-table-column>
      <el-table-column prop="examCode" label="试卷id"></el-table-column>
      <el-table-column prop="description" label="介绍" width="200"></el-table-column>
      <el-table-column prop="institute" label="所属学院" width="120"></el-table-column>
      <el-table-column prop="major" label="所属专业" width="200"></el-table-column>
      <el-table-column prop="grade" label="年级" width="100"></el-table-column>
      <el-table-column prop="examDate" label="考试日期" width="120"></el-table-column>
      <el-table-column prop="totalTime" label="持续时间" width="120"></el-table-column>
      <el-table-column prop="totalScore" label="总分" width="120"></el-table-column>
      <el-table-column prop="type" label="试卷类型" width="120"></el-table-column>
      <el-table-column prop="tips" label="考生提示" width="400"></el-table-column>
      <el-table-column fixed="right" label="操作" width="250">

        <template slot-scope="scope">
          <el-button @click="edit(scope.row.examCode)" type="primary" size="small">编辑</el-button>
          <el-button @click="deleteRecord(scope.row.examCode)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.current"
      :page-sizes="[4, 8, 10, 20]"
      :page-size="pagination.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total" class="page">
    </el-pagination>
    <!-- 编辑对话框-->
    <el-dialog
      title="编辑试卷信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <section class="update">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="试卷名称">
            <el-input v-model="form.source"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input v-model="form.description"></el-input>
          </el-form-item>
          <el-form-item label="所属学院">
            <el-input v-model="form.institute"></el-input>
          </el-form-item>
          <el-form-item label="所属专业">
            <el-input v-model="form.major"></el-input>
          </el-form-item>
          <el-form-item label="年级">
            <el-input v-model="form.grade"></el-input>
          </el-form-item>
          <el-form-item label="考试日期">
            <el-col :span="11">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.examDate"
                              style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="持续时间">
            <el-input v-model="form.totalTime"></el-input>
          </el-form-item>
          <el-form-item label="总分">
            <el-input v-model="form.totalScore"></el-input>
          </el-form-item>
          <el-form-item label="试卷类型">
            <el-input v-model="form.type"></el-input>
          </el-form-item>
          <el-form-item label="考生提示">
            <el-input type="textarea" v-model="form.tips"></el-input>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {}, //保存点击以后当前试卷的信息
      pagination: { //分页后的考试信息
        current: 1, //当前页
        total: null, //记录条数
        size: 4 //每页条数
      },
      dialogVisible: false,
      activeName: '0',  //默认打开序号
      topicCount: [],//每种类型题目的总数
      score: [],  //每种类型分数的总数
      topic: {  //试卷信息

      },
    }
  },
  created() {
    this.getExamInfo()
  },
  methods: {
    //初始化页面数据
    changeExpand(row, expandRows) {
      console.log('row', row)
      console.log('expandRows', expandRows)
      if (expandRows.length > 0) {
        let examcode = row.examCode
        this.init(examcode)
      } else {
        let examcode = ''
        this.topic = {}
        this.topicCount = []
        this.score = []
      }
    },

    init(examCode) {
      this.$axios(`/api/exam/${examCode}`).then(res => {  //通过examCode请求试卷详细信息
        console.log('预览详情', res)
        res.data.data.examDate = res.data.data.examDate.substr(0, 10)
        this.examData = {...res.data.data}
        let paperId =this.examData.paperId
        let adminId = this.$cookies.get("cid")
        console.log('adminID',adminId)
        console.log('paperID',paperId)
        this.$axios('/api/paper/', {params: {'paperId': paperId, 'adminId': adminId}}).then(res => {  //通过paperId获取试题题目信息
          console.log('============', res)
          this.topic = {...res.data}
          let keys = Object.keys(this.topic) //对象转数组
          keys.forEach(e => {
            let data = this.topic[e]
            this.topicCount.push(data.length)
            let currentScore = 0
            for (let i = 0; i < data.length; i++) { //循环每种题型,计算出总分
              currentScore += data[i].score
            }
            this.score.push(currentScore) //把每种题型总分存入score
          })
        })
      })
    },


    edit(examCode) { //编辑试卷
      this.dialogVisible = true
      this.$axios(`/api/exam/${examCode}`).then(res => { //根据试卷id请求后台
        if (res.data.code == 200) {
          this.form = res.data.data
        }
      })
    },
    handleClose(done) { //关闭提醒
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        }).catch(_ => {
      });
    },
    submit() { //提交修改后的试卷信息
      this.dialogVisible = false
      this.timeReverse()
      this.$axios({
        url: '/api/exam',
        method: 'put',
        data: {
          ...this.form
        }
      }).then(res => {
        if (res.data.code == 200) {
          this.$message({ //成功修改提示
            message: '更新成功',
            type: 'success'
          })
        } else {
          this.$message.error(res.data.message)
        }
        this.getExamInfo()
      })
    },
    deleteRecord(examCode) {
      this.$confirm("确定删除该记录吗,该操作不可逆！！！", "删除提示", {
        confirmButtonText: '确定删除',
        cancelButtonText: '算了,留着',
        type: 'danger'
      }).then(() => { //确认删除
        this.$axios({
          url: `/api/exam/${examCode}`,
          method: 'delete',
        }).then(res => {
          this.getExamInfo()
        })
      }).catch(() => {

      })
    },
    getExamInfo() { //分页查询所有试卷信息
      this.$axios(`/api/exams/${this.pagination.current}/${this.pagination.size}`).then(res => {
        console.log('res', res)
        this.pagination = res.data.data
      }).catch(error => {
      })
    },
    //改变当前记录条数
    handleSizeChange(val) {
      this.pagination.size = val
      this.getExamInfo()
    },
    //改变当前页码，重新发送请求
    handleCurrentChange(val) {
      this.pagination.current = val
      this.getExamInfo()
    },
    view(id) {
      this.$router.push({path: "/answer", query: {examCode: id}})
    },
    // 时间格式化
    msToDate(msec) {
      const datetime = new Date(msec)
      const year = datetime.getFullYear()
      const month = datetime.getMonth()
      const date = datetime.getDate()
      const hour = datetime.getHours()
      const minute = datetime.getMinutes()
      const second = datetime.getSeconds()
      const result1 = year
        + '-'
        + ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1))
        + '-'
        + ((date + 1) < 10 ? '0' + date : date)
        + ' '
        + ((hour + 1) < 10 ? '0' + hour : hour)
        + ':'
        + ((minute + 1) < 10 ? '0' + minute : minute)
        + ':'
        + ((second + 1) < 10 ? '0' + second : second)

      const result2 = year
        + '-'
        + ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1))
        + '-'
        + ((date + 1) < 10 ? '0' + date : date)

      const result = {
        hasTime: result1,
        withoutTime: result2
      }
      return result
    },
    timeFormatSeconds(time) {
      const d = time ? new Date(time) : new Date()
      const year = d.getFullYear()
      let month = d.getMonth() + 1
      let day = d.getDate()
      let hours = d.getHours()
      let min = d.getMinutes()
      let seconds = d.getSeconds()

      if (month < 10) month = '0' + month
      if (day < 10) day = '0' + day
      if (hours < 0) hours = '0' + hours
      if (min < 10) min = '0' + min
      if (seconds < 10) seconds = '0' + seconds

      return (year + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + seconds)
    },
    timeReverse() {
      this.form.examDate = this.msToDate((this.form.examDate)).withoutTime
    },
  },
};
</script>
<style lang="scss" scoped>
.exam {
  padding: 0px 40px;

  .page {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .edit {
    margin-left: 20px;
  }

  .inner .contenti .question {
    margin-left: 40px;
    color: #9a9a9a;
    font-size: 14px;
  }

  .inner .titlei {
    margin-left: 20px;
    font-size: 16px;
    color: #88949b;
    font-weight: bold;
  }

  .time {
    font-size: 16px;
    margin-left: 20px;
    color: #999;
  }
}
</style>
